<template>
  <div class="home">
    <div class="container">
      <div class="welcome-header">
        <h1>🎓 高中信息技术选择题练习平台</h1>
        <p class="subtitle">欢迎来到在线练习系统，请填写信息开始答题</p>
      </div>
      
      <form @submit.prevent="startQuiz" class="start-form">
        <div class="form-group">
          <label for="studentName">👤 请输入你的姓名</label>
          <input
            type="text"
            id="studentName"
            v-model="studentName"
            placeholder="请输入你的真实姓名"
            required
            :class="{ 'error': nameError }"
          >
          <div v-if="nameError" class="error-message">
            ⚠️ {{ nameError }}
          </div>
          <div v-if="lockedNameInfo" class="info-message">
            🔒 {{ lockedNameInfo }}
          </div>
        </div>
        

        
        <button 
          type="submit" 
          class="btn start-btn"
          :disabled="!canStart"
        >
          🚀 开始答题
        </button>
      </form>
      
      <div class="navigation-section">
        <div class="nav-buttons">
          <button @click="$router.push('/analysis')" class="btn analysis-btn">
            📊 查看班级学情分析
          </button>
          <button @click="$router.push('/teacher')" class="btn teacher-btn">
            👨‍🏫 教师管理后台
          </button>
        </div>
      </div>
      
      <div class="info-section">
        <div class="info-card">
          <h3>📋 答题说明</h3>
          <ul>
            <li>请认真填写姓名信息</li>
            <li>每道题只能选择一个答案</li>
            <li>答题完成后可查看详细解析</li>
            <li>总分100分，祝你取得好成绩！</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data() {
    return {
      studentName: '',
      nameError: '',
      remainingTime: 0,
      countdownTimer: null,
      lockedNameInfo: ''
    }
  },
  computed: {
    canStart() {
      return this.studentName.trim() && !this.nameError
    }
  },
  watch: {
    studentName(newName) {
      // 当姓名输入改变时，检查是否可以使用
      this.checkNameAvailability(newName.trim())
    }
  },
  methods: {
    checkNameAvailability(name) {
      // 更新锁定信息显示
      this.updateLockedNameInfo()

      if (!name) {
        this.nameError = ''
        this.remainingTime = 0
        return
      }

      // 首先进行姓名格式验证
      const nameValidationResult = this.validateNameFormat(name)
      if (!nameValidationResult.isValid) {
        this.nameError = nameValidationResult.error
        this.remainingTime = 0
        this.stopCountdown()
        return
      }

      // 获取本地存储的锁定姓名记录
      const lockedNameData = JSON.parse(localStorage.getItem('lockedName') || 'null')
      const currentTime = Date.now()
      const timeLimit = 30 * 60 * 1000 // 30分钟

      // 检查是否有锁定的姓名
      if (lockedNameData) {
        const { name: lockedName, timestamp } = lockedNameData
        const timeDiff = currentTime - timestamp

        if (timeDiff < timeLimit) {
          // 还在锁定期内
          if (name === lockedName) {
            // 输入的是锁定的姓名，允许使用
            this.nameError = ''
            this.remainingTime = 0
            this.stopCountdown()
            return
          } else {
            // 输入的不是锁定的姓名，不允许使用
            const remainingSeconds = Math.ceil((timeLimit - timeDiff) / 1000)
            this.remainingTime = remainingSeconds
            this.updateErrorMessage(lockedName)
            this.startCountdown()
            return
          }
        } else {
          // 超过30分钟，清除锁定记录
          localStorage.removeItem('lockedName')
        }
      }

      // 没有锁定的姓名或锁定已过期，任何姓名都可以使用
      this.nameError = ''
      this.remainingTime = 0
      this.stopCountdown()
    },

    validateNameFormat(name) {
      // 验证姓名格式：2-3个汉字，不能包含字母和数字
      
      // 检查是否只包含汉字（中文字符）
      const chineseRegex = /^[\u4e00-\u9fa5]+$/
      if (!chineseRegex.test(name)) {
        return {
          isValid: false,
          error: '姓名只能包含中文汉字，不能包含字母、数字或其他字符'
        }
      }
      
      // 检查长度是否在2-3个字符之间
      const nameLength = name.length
      if (nameLength < 2) {
        return {
          isValid: false,
          error: '姓名长度不能少于2个汉字'
        }
      }
      
      if (nameLength > 3) {
        return {
          isValid: false,
          error: '姓名长度不能超过3个汉字'
        }
      }
      
      return {
        isValid: true,
        error: ''
      }
    },

    updateErrorMessage(lockedName) {
      if (this.remainingTime > 0) {
        const minutes = Math.floor(this.remainingTime / 60)
        const seconds = this.remainingTime % 60
        const timeStr = minutes > 0 ? `${minutes}分${seconds}秒` : `${seconds}秒`
        this.nameError = `当前姓名已锁定为「${lockedName}」，请等待 ${timeStr} 后才能使用其他姓名，或直接使用「${lockedName}」`
      }
    },

    startCountdown() {
      this.stopCountdown()
      this.countdownTimer = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--
          // 获取当前锁定的姓名来更新错误消息
          const lockedNameData = JSON.parse(localStorage.getItem('lockedName') || 'null')
          const lockedName = lockedNameData ? lockedNameData.name : '未知'
          this.updateErrorMessage(lockedName)
        } else {
          this.stopCountdown()
          this.checkNameAvailability(this.studentName.trim())
        }
      }, 1000)
    },

    stopCountdown() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
    },

    updateLockedNameInfo() {
      const lockedNameData = JSON.parse(localStorage.getItem('lockedName') || 'null')
      if (lockedNameData) {
        const { name: lockedName, timestamp } = lockedNameData
        const currentTime = Date.now()
        const timeLimit = 30 * 60 * 1000 // 30分钟
        const timeDiff = currentTime - timestamp

        if (timeDiff < timeLimit) {
          const remainingSeconds = Math.ceil((timeLimit - timeDiff) / 1000)
          const minutes = Math.floor(remainingSeconds / 60)
          const seconds = remainingSeconds % 60
          const timeStr = minutes > 0 ? `${minutes}分${seconds}秒` : `${seconds}秒`
          this.lockedNameInfo = `当前姓名已锁定为「${lockedName}」，剩余时间：${timeStr}`
        } else {
          this.lockedNameInfo = ''
          localStorage.removeItem('lockedName')
        }
      } else {
        this.lockedNameInfo = ''
      }
    },

    startQuiz() {
      if (!this.canStart) return

      const name = this.studentName.trim()

      // 再次检查姓名可用性
      this.checkNameAvailability(name)
      if (this.nameError) return

      // 锁定当前姓名（如果还没有锁定的话）
      const lockedNameData = JSON.parse(localStorage.getItem('lockedName') || 'null')
      if (!lockedNameData) {
        const lockData = {
          name: name,
          timestamp: Date.now()
        }
        localStorage.setItem('lockedName', JSON.stringify(lockData))
      }

      // 将学生信息存储到sessionStorage
      sessionStorage.setItem('studentName', name)
      // 默认设置为1班，因为题目已经绑定到特定班级
      sessionStorage.setItem('classId', '1')

      // 跳转到答题页面
      this.$router.push('/quiz')
    },

    cleanupExpiredNames() {
      const lockedNameData = JSON.parse(localStorage.getItem('lockedName') || 'null')
      const currentTime = Date.now()
      const timeLimit = 30 * 60 * 1000 // 30分钟

      // 清理过期的锁定姓名
      if (lockedNameData) {
        const timeDiff = currentTime - lockedNameData.timestamp
        if (timeDiff > timeLimit) {
          localStorage.removeItem('lockedName')
        }
      }

      // 清理旧的usedNames记录（如果存在的话）
      localStorage.removeItem('usedNames')
    }
  },

  mounted() {
    // 清理过期的姓名记录
    this.cleanupExpiredNames()
    // 初始化锁定信息显示
    this.updateLockedNameInfo()
  },

  beforeUnmount() {
    // 清理定时器
    this.stopCountdown()
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.home::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>') repeat;
  pointer-events: none;
}

.welcome-header {
  text-align: center;
  margin-bottom: 50px;
  position: relative;
  z-index: 1;
}

.welcome-header h1 {
  font-size: clamp(2rem, 5vw, 3rem);
  color: #fff;
  margin-bottom: 15px;
  text-shadow: 0 4px 8px rgba(0,0,0,0.3);
  font-weight: 700;
  letter-spacing: -0.5px;
  background: linear-gradient(45deg, #fff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: clamp(1rem, 3vw, 1.3rem);
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 30px;
  font-weight: 400;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
  line-height: 1.6;
}

.start-form {
  margin-bottom: 40px;
  position: relative;
  z-index: 1;
}

.form-group input.error {
  border: 2px solid #ff6b6b;
  box-shadow: 0 0 10px rgba(255, 107, 107, 0.3);
}

.error-message {
  color: #ff6b6b;
  font-size: 0.9em;
  margin-top: 8px;
  padding: 10px;
  background: rgba(255, 107, 107, 0.1);
  border-radius: 8px;
  border-left: 4px solid #ff6b6b;
  animation: fadeIn 0.3s ease-in;
}

.info-message {
  color: #2196F3;
  font-size: 0.9em;
  margin-top: 8px;
  padding: 10px;
  background: rgba(33, 150, 243, 0.1);
  border-radius: 8px;
  border-left: 4px solid #2196F3;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.start-btn {
  width: 100%;
  font-size: 1.2em;
  padding: 18px;
  margin-top: 25px;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  box-shadow: 0 8px 25px rgba(76, 175, 80, 0.4);
  position: relative;
  overflow: hidden;
}

.start-btn:hover {
  box-shadow: 0 12px 35px rgba(76, 175, 80, 0.5);
  background: linear-gradient(135deg, #45a049, #4CAF50);
}

.start-btn::after {
  content: '→';
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  transition: transform 0.3s ease;
}

.start-btn:hover::after {
  transform: translateY(-50%) translateX(5px);
}

.navigation-section {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
  z-index: 1;
}

.nav-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .nav-buttons {
    flex-direction: column;
    gap: 10px;
  }
}

.analysis-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  font-size: 1.1em;
  flex: 1;
  min-width: 200px;
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.3);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.analysis-btn:hover {
  box-shadow: 0 12px 35px rgba(255, 107, 107, 0.4);
  transform: translateY(-2px);
}

.teacher-btn {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
  font-size: 1.1em;
  flex: 1;
  min-width: 200px;
  box-shadow: 0 8px 25px rgba(155, 89, 182, 0.3);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.teacher-btn:hover {
  box-shadow: 0 12px 35px rgba(155, 89, 182, 0.4);
  transform: translateY(-2px);
}

.info-section {
  margin-top: 50px;
  position: relative;
  z-index: 1;
}

.info-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 15px 35px rgba(0,0,0,0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;
}

.info-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2, #667eea);
  background-size: 200% 100%;
  animation: shimmer 2s ease-in-out infinite;
}

@keyframes shimmer {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

.info-card h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.4em;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-card ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-card li {
  padding: 12px 0;
  border-bottom: 1px solid rgba(238, 238, 238, 0.5);
  color: #555;
  position: relative;
  padding-left: 25px;
  line-height: 1.6;
  transition: all 0.3s ease;
}

.info-card li::before {
  content: '✓';
  position: absolute;
  left: 0;
  top: 12px;
  color: #4CAF50;
  font-weight: bold;
  font-size: 14px;
}

.info-card li:hover {
  color: #333;
  transform: translateX(5px);
}

.info-card li:last-child {
  border-bottom: none;
}

@media (max-width: 768px) {
  .home {
    padding: 15px;
  }
  
  .welcome-header {
    margin-bottom: 30px;
  }
  
  .info-card {
    padding: 20px;
  }
  
  .start-btn {
    padding: 15px;
    font-size: 1.1em;
  }
  
  .nav-buttons .btn {
    min-width: auto;
    width: 100%;
  }
}
</style>